<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Link extends Base
{
    public function index()
    {
        $data = \app\admin\model\Link::select();
        return view("index",['data'=>$data]);
    }

    // 友情连接添加
    public function add()
    {
        return view('add');
    }

    // 添加到数据库
    public function insert(Request $request)
    {
        $data = $request->param();
        // 验证
        $rule = [
            'domain|域名' => 'require',
            'url|网址' => 'require|url',
            'orderby|排序' => 'require|number'
        ];

        $validate = new \think\Validate($rule);

        if($validate->check($data))
        {
            $error = $validate->getError();
            return $this->error($error);
        }

        // 验证完毕进行入库
        \app\admin\model\Link::strict(false)->insert($data);

        return $this->success("添加成功",'admin/link/index');
    }

    // 修改页面
    public function edit(Request $request,int $id)
    {
        // 如果有id就进来，没有就出去
        if(empty($id))
        {
            return $this->error("出错啦",'admin/link/index');
        }

        $data = \app\admin\model\Link::find($id);

        return view("/link/edit",['data'=>$data]);

    }

    public function update(Request $request,int $id)
    {
        // 如果有id就进来，没有就出去
        if(empty($id))
        {
            return $this->error("出错啦",'admin/link/index');
        }

        $data = $request->param();

        $rule = [
            'domain|域名' => "require",
            "url|网址" => 'require|url',
            'orderby|排序' => 'require|number'
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data))
        {
            $error = $validate->getError();
            return $this->error($error);
        }

        \app\admin\model\Link::where('id',$id)->strict(false)->update($data);

        return $this->success("修改 成功",'admin/link/index');
    }
    // 删除连接
    public function delete(int $id)
    {
        if(empty($id))
        {
            return $this->error("错误",'/admin/link/index');
        }

        \app\admin\model\Link::where('id',$id)->delete();

        return $this->success("删除成功",'admin/link/index');
    }
}
